import React from "react";
import styles from '@/assets/css/confirm.module.css';
import type room from "@/types/room";
import type guest from "@/types/guest";
import type { receive } from "@/types/coupon";
import type business from "@/types/business";

// 订单详情的类型接口
interface OrderInfo {
  remark: string;
  //价格信息
  origin_price: number | string;
  price: number | string;
  //优惠券
  couponid: number;
  couponstr: string;
  //日期
  datestr: string;
  starttime: number;
  endtime: number;
  //住客
  guest: string;
  gueststr: string;
  guestids: number[];
  //支付方式
  paystr: string;
  pay: string;
}

// 优惠券弹出层类型接口
interface CouponPickerProp {
  label: string;
  value: number;
  rate: string
}

const Confirm = () => {
  // 声明变量
  const [searchParams] = useSearchParams();
  const [roomid] = useState<string>(searchParams.get('roomid') ?? '');
  const [business] = useState<business>(React.business);
  const [room, SetRoom] = useState<room>({} as room);

  //订单信息
  const [order, SetOrder] = useState<OrderInfo>({
    remark: '',
    //价格信息
    origin_price: 0,
    price: 0,
    //优惠券
    couponid: 0,
    couponstr: '暂无优惠券信息',
    //日期
    datestr: '',
    starttime: 0,
    endtime: 0,
    //住客
    guest: '',
    gueststr: '请选择住客信息',
    guestids: [],
    //支付方式
    paystr: '余额支付',
    pay: 'money'
  });
  // 日期
  const [DateShow, SetDateShow] = useState<boolean>(false);

  // 日期组件默认日期
  const defaultDateRange: [Date, Date] = [
    new Date(),
    new Date(new Date().getTime() + 86400000),
  ];

  // 住客
  const [GuestShow, SetGuestShow] = useState<boolean>(false);
  const [guest, SetGuest] = useState<guest[]>([]);

  // 优惠券
  const [CouponShow, SetCouponShow] = useState<boolean>(false);
  const [coupon, SetCoupon] = useState<[CouponPickerProp[]]>([[]]);

  // 支付方式
  const [PayList] = useState([[
    { label: '余额支付', value: 'money' },
    { label: '微信支付', value: 'wx' },
    { label: '支付宝支付', value: 'zfb' },
  ]]);
  const [PayShow, SetPayShow] = useState<boolean>(false);

  // 价格
  const [OriginPrice, SetOriginPrice] = useState<number>(0);
  const [price, SetPrice] = useState<number>(0);

  // 天数
  const [day, SetDay] = useState<number>(0);

  // 确认日期事件
  const OnDateConfirm = (values: Date[]) => {
    const datestr = `${new Date(values[0]).toLocaleDateString()} - ${new Date(values[1]).toLocaleDateString()}`;

    // 标准时间转换为时间戳
    const starttime = Date.parse(new Date(values[0]).toLocaleDateString()) / 1000;
    const endtime = Date.parse(new Date(values[1]).toLocaleDateString()) / 1000;
    // 更新订单信息
    SetOrder({
      ...order,
      datestr,
      starttime,
      endtime
    });
  }

  // 选择住客信息
  const OnGuestChange = (values: number[]) => {
    const gueststr: string[] = [];
    const guestids: number[] = [];
    //循环遍历
    guest.map((item: guest) => {
      if (values.includes(item.id)) {
        gueststr.push(item.nickname);
        guestids.push(item.id);
      }
    })
    // 小黑、小红、
    const str = gueststr.join('、');
    // 1,2,3
    const ids = guestids.join(',');
    // 更新到订单数据中
    SetOrder({
      ...order,
      gueststr: str,
      guest: ids,
      guestids,
    })
  }

  // 选择优惠券
  const OnCouponChange = (values: number[]) => {
    let couponstr = '';
    if (coupon.length <= 0) {
      React.fail('暂无优惠券');
      return;
    }
    // 获取picker第一个选项
    const list: CouponPickerProp[] = coupon[0];
    // 循环遍历
    list.map((item) => {
      if (item.value == values[0]) {
        couponstr = item.label
      }
    })
    // 更新订单数据
    SetOrder({
      ...order,
      couponstr,
      couponid: values[0]
    })
  }

  // 选择支付方式
  const OnPayChange = (values: string | null[]) => {
    let paystr = '';
    // 获取picker第一项
    const list: { label: string; value: string }[] = PayList[0]
    list.map((item) => {
      if (item.value == values[0]) {
        paystr = item.label
      }
    })
    // 更新订单数据
    SetOrder({
      ...order,
      paystr,
      pay: values[0] ? values[0] : 'money',
    })
  }

  // 更新备注
  const OnRemarkChange = (value: string) => {
    SetOrder({
      ...order,
      remark: value
    })
  }

  // 提交订单
  const OnConfirmOrder = () => {
    // 确认订单
    React.UI.Dialog.confirm({
      title: '确认订单',
      content: '是否确认提交订单？',
      onConfirm: async () => {
        // 表单验证
        if (!order.guest) {
          React.fail('请选择住客！');
          return;
        }
        // 从order提取所需的数据
        const params = {
          busid: business.id,
          roomid,
          guestids: order.guest,
          couponid: order.couponid,
          endtime: order.endtime,
          starttime: order.starttime,
          pay: order.pay,
          remark: order.remark
        }
        // 发起请求
        const result = await React.Http.post('/order/add', params);
        // 处理请求结果
        if (result.code === 1) {
          if (result.url) {
            // 直接跳转到订单详情页面
            React.success(result.msg, () => {
              React.navigate(result.url);
            });
          } else {
            // 跳转到收银台
            React.navigate(`/room/pay?payid=${result.data.id}`);
          }
        } else {
          React.fail(result.msg);
        }
      }
    })
  }

  // 计算总价
  const OrderPrice = () => {
    if (price == OriginPrice) {
      return (
        <div className={styles.text}>
          <span>总价:</span>
          <span>￥{price}</span>
        </div>
      )
    } else {
      return (
        <div className={styles.text}>
          <span>优惠价格:</span>
          <span>￥{price}</span>
          <s>原价：￥{OriginPrice}</s>
        </div>
      )
    }
  }

  // 获取详情数据
  const GetConfirmInfo = async () => {
    // 组装参数
    const params = {
      roomid,
      busid: business.id
    }
    // 发起请求
    const result = await React.Http.post('/room/confirm', params);
    // 处理请求结果
    if (result.code === 1) {
      // 房间数据
      SetRoom(result.data.room);
      // 优惠券数据
      const CouponData: CouponPickerProp[] = [];
      result.data.CouponList.map((item: receive) => {
        CouponData.push({
          label: `${item.coupon.title}-${parseFloat(item.coupon.rate) * 10}折`,
          value: item.id,
          rate: item.coupon.rate
        })
      });
      SetCoupon([CouponData]);
      SetGuest(result.data.GuestList);
    } else {
      React.fail(result.msg, () => {
        React.navigate(-1);
      });
    }
  }

  // 初始化默认时间
  const GetCurrentDate = () => {
    // `2025-06-05 - 2025-06-06`
    const datestr = `${new Date(defaultDateRange[0]).toLocaleDateString()} - ${new Date(defaultDateRange[1]).toLocaleDateString()}`;
    // 标准时间转换为时间戳
    const starttime = Date.parse(new Date(defaultDateRange[0]).toLocaleDateString()) / 1000;
    const endtime = Date.parse(new Date(defaultDateRange[1]).toLocaleDateString()) / 1000;
    // 更新订单信息
    SetOrder({
      ...order,
      datestr,
      starttime,
      endtime
    });
  }

  // 挂载前 获取数据
  useEffect(() => {
    GetConfirmInfo();
    GetCurrentDate();
  }, [roomid]);

  const Total = () => {
    // 获取开始时间和退房时间
    const starttime = order.starttime;
    const endtime = order.endtime;

    // 时间差
    const durationSeconds = endtime - starttime;

    // 计算预定多少天 86400 = 60 * 60 * 24
    const day = Math.floor(durationSeconds / 86400);

    // 原价 时间差 * 房间原价
    const truncateToTwoDecimals = (num: number) => Math.trunc(num * 100) / 100;
    const origin_price = truncateToTwoDecimals(parseFloat(room.price) * day);
    let price = origin_price;

    //判断是否有选择优惠券
    if (order.couponid) {
      // 找出当前选中优惠券的记录
      let CouponActive: CouponPickerProp | undefined = {
        label: '',
        value: 0,
        rate: '1'
      };

      if (coupon.length > 0 && coupon[0].length > 0) {
        CouponActive = coupon[0].find((item: CouponPickerProp) => item.value = order.couponid);
      }

      if (CouponActive) {
        //优惠券使用后的实际的价格
        price = truncateToTwoDecimals(price * parseFloat(CouponActive.rate))
      }
    }

    // 修改价格
    SetPrice(price);
    SetOriginPrice(origin_price);
    SetDay(day);
  }

  useEffect(() => {
    Total();
  }, [order, room]);

  return (
    <>
      <div className={styles.skeleton}>
        {/* 房间信息 */}
        <div className={styles.detail}>
          <div className={styles.thumb}>
            <img src={room.thumb_text} alt="" />
          </div>
          <div className={styles.right}>
            <p>{room.name} - ￥{room.price} / 晚</p>
            <div className={styles.tips}>
              {room.flag && JSON.parse(room.flag).map((flag: string, index: number) => <span key={index}> {flag} </span>)}
            </div>
          </div>
        </div>

        {/* 入住时间 */}
        <div className={styles.skeleton_rect}>
          <div className={styles.item}>
            <label>入住日期</label>
            <React.UI.Input type="text" className={styles.item_right} placeholder="请选择入住日期" value={order.datestr} onClick={() => SetDateShow(true)} />
          </div>

          {/* 日期选择 */}
          <React.UI.CalendarPicker
            visible={DateShow}
            min={new Date()}
            defaultValue={defaultDateRange}
            selectionMode='range'
            onClose={() => SetDateShow(false)}
            onMaskClick={() => SetDateShow(false)}
            onConfirm={OnDateConfirm}

          >
          </React.UI.CalendarPicker>

          {/* 住客信息 */}
          <div className={styles.item}>
            <label>住客信息</label>
            <div className={order.guestids.length > 0 ? styles.item_right : styles.item_rights} onClick={() => SetGuestShow(true)}>{order.gueststr}</div>
          </div>

          {/* 弹出层 */}
          <React.UI.Popup
            visible={GuestShow}
            destroyOnClose
            onMaskClick={() => SetGuestShow(false)}
          >
            {/* 住客信息 */}
            <React.UI.CheckList
              multiple
              defaultValue={order.guestids}
              onChange={OnGuestChange}
              className={styles.checkListContainer}
            >
              {guest && guest.map((item: guest, key: number) => (
                <React.UI.CheckList.Item key={key} value={item.id}>
                  {item.nickname}（{item.mobile}）
                </React.UI.CheckList.Item>
              ))}
            </React.UI.CheckList>

            <React.UI.Button color="primary" block style={{ width: '100%' }} onClick={() => SetGuestShow(false)}>确认</React.UI.Button>
          </React.UI.Popup>
        </div>

        {/* 优惠券 */}
        <div className={styles.skeleton_price}>
          <div className={styles.tips}>优惠券</div>
          <p>{order.couponstr}</p>
          <React.UI.Button size="mini" color="primary" onClick={() => SetCouponShow(true)}>选择</React.UI.Button>

          {/* 弹框选项 */}
          <React.UI.Picker
            visible={CouponShow}
            columns={coupon}
            onClose={() => SetCouponShow(false)}
            onConfirm={OnCouponChange}
          >
          </React.UI.Picker>
        </div>

        {/* 支付方式 */}
        <div className={styles.skeleton_price}>
          <div className={styles.tips}>支付方式</div>
          <p>{order.paystr}</p>
          <React.UI.Button size="mini" color="primary" onClick={() => SetPayShow(true)}>选择</React.UI.Button>

          <React.UI.Picker
            columns={PayList}
            visible={PayShow}
            onClose={() => SetPayShow(false)}
            onConfirm={OnPayChange}
          >
          </React.UI.Picker>
        </div>

        {/* 订单备注 */}
        <div className={styles.skeleton_price}>
          <div className={styles.tips}>订单备注</div>
          <React.UI.Input placeholder={'请输入订单备注'} value={order.remark} onChange={OnRemarkChange} />
        </div>

        {/* 费用 */}
        <div className={styles.skeleton_price}>
          <div className={styles.tips}>房间费用</div>
          <div className={styles.prices}>
            <span>￥{OriginPrice}</span>
            <span>共 {day} 晚</span>
          </div>
        </div>

      </div >

      <div className={styles.comfirm_foot_bar}>
        <OrderPrice />
        <React.UI.Button onClick={OnConfirmOrder} color='primary' shape='rounded'>提交订单</React.UI.Button>
      </div>
    </>
  )
}

export default Confirm;